<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
        <title>Main Menu</title>
        <style type="text/css">
		.table {
			margin-left: 200px;
			display: block;
			padding: 5px;
			margin-bottom: 2px;
			background-color: #666;
			color: #00CCFF;
			text-decoration: none;
		}
		</style>
        
        <link rel="stylesheet" type="text/css" href="css/style.css" />
        <script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
        
         <script>
         var $responseType = 'json';
         
         $(document).ready(function() {
        	retrieveOpenSessions();
         });
         
		function retrieveOpenSessions() {
			$("#sessions_list").empty();
			$adminPrefix = "";
			$baseUrl = window.location.pathname;
			if ($baseUrl.indexOf("admin") >= 0) {
				$adminPrefix = "/admin";
			}
			$.ajax({
			    type: "GET",
			    url: $responseType + $adminPrefix + "/recentsessions",
			    success: function(response){
			    	$.each(response, function() {
			    		$("<a/>", {
				    	    id: this,
				    	    href: 'javascript:getQuestionsForSession("' + this + '")',
				    	    text: this,
				    	    class : 'button_a'
				    	}).appendTo("#sessions_list");
				       
				    	$('#sessions_list').append($('<br/><br/><br/>'));
			    	});		
			    },
			    error: function(e){
			    	alert(e);
			    }
			});
		}
		
		function clearAllDivs() {
			$("#recent_sessions").css("display", "none");
	    	$("#create_session").css("display", "none");
	    	$("#viewQuestions").css("display", "none");
	    	$("#viewReport").css("display", "none");
	    	$("#createQuestion").css("display", "none");
	    	
		}
		function backtoSessionList() {
	    	clearAllDivs();
	    	document.getElementById('viewReport_tbl').innerHTML = '';
	    	retrieveOpenSessions();
	    	$("#recent_sessions").css("display", "block");
	    	
		}
		
		function backtoQuestionList(){
			document.getElementById('viewReport_tbl').innerHTML = '';
	    	clearAllDivs();
	    	$("#viewQuestions").css("display", "block");
		}
		
		function showCreateSession() {
			$("#recent_sessions").css("display", "none");
	    	$("#create_session").css("display", "block");
		}
		
		function showCreateQuestion() {
			clearAllDivs();
			$('#create_q_question').val('');
			$('#create_question_key').val('');
			$("input[name='create_q_answers']").val('');
			$("#createQuestion").css("display", "block");
	    	
			
		}
		function submitPoll(answerValue) {
			
			$selectedValues = answerValue.split("_");
			$questionID = $selectedValues[0];
			$answerID = $selectedValues[1];
		
			$.ajax({
			    type: "GET",
			    url: $responseType + "/submit/" + $questionID + "/" + $answerID,
			    success: function(response){
			    	alert(response);
			    },
			    error: function(e){
			    	alert(response);
			    }
			});
		}
		/*
		function submitPoll(answerValue) {
			
			$selectedValues = answerValue.split("_");
			$questionID = $selectedValues[0];
			$answerID = $selectedValues[1];
		
			$.ajax({
			    type: "GET",
			    url: "submit/" + $questionID + "/" + $answerID,
			    success: function(response){
			    	alert('answer submitted!');
			    },
			    error: function(e){
			    	alert(e);
			    }
			});
		}*/
		
		function getReport(questionID, qText) {
			var answerPoll = new Array();
			var totalAnswers = 0;
			var i = 0;
			var j = 0;
			clearAllDivs();
			$.ajax({
				type: "GET",
				url:  $responseType + "/getResults/" + questionID,
				success: function(response){
				  	$.each(response, function() {
				  		answerPoll[j]=this;
				  		totalAnswers += this;
				  		j++;
				   	});
				  	$("<h3/><br>", {
				  		align: 'center',
			    	    text: qText
			    	}).appendTo("#viewReport_tbl");
				  	//$newRow ='<a href="#">' + qText + '</a><br>';
				  	//$('#viewReport_tbl tr:last').after($newRow);
				  	$.ajax({
					    type: "GET",
					    url:  $responseType + "/getAnswers/" + questionID,
					    success: function(response){
					    	$.each(response, function() {
							  	$("<a/>", {
						    	    class : 'table',
						    	    href: '#',
						    	    style: 'width: ' + answerPoll[i]/totalAnswers*50 + '%',
						    	    text: this.answerText + '('+answerPoll[i]+')'
						    	}).appendTo("#viewReport_tbl");
							  	
					    		i++;
					    	});
						  	$("#viewReport").css("display", "block");
					    },
					    error: function(e){
					    	alert("Error");
					    }
					});	

				},
				error: function(e){
				alert("Error");
				}
			});
				
		}
		
		function createQuestionSession() {
			var $sessionName = $('#create_session_keyword').val();
			var $key = $('#create_session_key').val();
			
			$.ajax({
			    type: "GET",
			    url: $responseType + "/newsession/" + $sessionName + "/" + $key,
			    success: function(response){
			    	$("#sessions_list").empty();
			    	retrieveOpenSessions();
			    	$("#create_session").css("display", "none");
			    	$("#recent_sessions").css("display", "block");
			    },
			    error: function(e){
			    	alert(e);
			    }
			});
		}
		
		function enableQuestion(questionID) {
			
			var $password = prompt("Enter your session key", "");
			var $keyword = $("#current_session_id").val();
			var $enable = "true";
			
			if( $password === null) return;
			if ($password == "") return;
			
			$.ajax({
			    type: "GET",
			    url: $responseType + "/enablequestion/" + $keyword + "/" + $password + "/" + questionID + "/" + $enable,
			    success: function(response){
			    	//alert(response);
			    },
			    error: function(e){
			    	//alert(e);
			    }
			});
		}
		
		function removeQuestion(questionID) {
			var $keyword = $("#current_session_id").val();
			var $password = prompt("Enter your session key", "");
			
			if( $password === null) return;
			if ($password == "") return;
			
			$.ajax({
			    type: "GET",
			    url: $responseType + "/removequestion/" + $keyword + "/" + $password + "/" + questionID,
			    success: function(response){
			    	getQuestionsForSession($keyword);
			    	//alert(response);
			    },
			    error: function(e){
			    	getQuestionsForSession($keyword);
			    	//alert(e);
			    }
			});
		}
		
		function editQuestion() {
			var $key = "password";
			var $questionSessionId = "2";
			
			var answers = new Array();
			var answer = new Object();
			answer.answerText = "True";
			
			var answer2 = new Object();
			answer2.answerText = "False";
			
			answers[0] = answer;
			answers[1] = answer2;
			
			var question = new Object();
			question.questionText = "Do you like coding?";
			question.questionSessionID = "2";
			question.enabled = true;
			question.answers = answers;
			
			var jsonString = JSON.stringify( question );
			$.ajax({
			    type: "POST",
			    url: $responseType + "/editquestion/" + $questionSessionId + "/" + $key,
			    data: jsonString,
			    contentType: "application/json; charset=utf-8",
			    success: function(response){
			    	
		    	
			    },
			    error: function(e){
			    	alert(e);
			    }
			});
		}
		
		function createQuestion() {
			var $key = $('#create_question_key').val();
			var $questionSessionId = $("#current_session_id").val();
			
			var answers = new Array();
			
			$("input[name=create_q_answers]").each(function() {
				var answer = new Object();
				answer.answerText = $(this).val();
				answers.push(answer);
			});
			
			
			var question = new Object();
			question.questionText = $('#create_q_question').val();
			question.enabled = $("input[name='enabledisable']:checked").val();
			
			question.answers = answers;
			
			var jsonString = JSON.stringify( question );
			$.ajax({
			    type: "POST",
			    url: $responseType + "/newquestion/" + $questionSessionId + "/" + $key,
			    data: jsonString,
			    contentType: "application/json; charset=utf-8",
			    success: function(response){
			    	if( response == false) {
			    		alert("invalid key! please try again");
			    	}
			    	else {
			    		clearAllDivs();
				    	getQuestionsForSession($questionSessionId);
			    	}
			    	
		    	
			    },
			    error: function(e){
			    	alert(e);
			    }
			});
		}

		
		function getQuestionsForSession(keyword) {
			$("#current_session_id").val(keyword);
			$.ajax({
			    type: "GET",
			    url: $responseType + "/getquestions/" + keyword ,
			    success: function(response){
			    	 $("#viewQuestions_tbl").find("tr:gt(1)").remove();
			    	 count = 0;
			    	$.each(response.questions, function() {
			    		
			    		$questionId = this.id;
			    		$questionText = this.questionText;
			    		$enabled = this.enabled;
			    		$answers = this.answers;
			    		
			    		$answersRow = "";
			    		
			    		$.each($answers, function(i) {
		                	$answersRow += '<input type="radio" id="radio-' + (count+i+1 ) + '" name="question_answers" value="' + $questionId + '_' + this.id + '" class="regular-radio" onclick="submitPoll(this.value)" /><label for="radio-' + (count+i+1) + '">' + this.answerText + '</label><br />';
		                	
			    		});
			    		count += $answers.length;
			    		$newRow = '<tr>' +
								        '<td align="center" >' +
								         	$questionText +
						                '<button type=button style="border: 0; position: relative; top: 12px; background: transparent">'+
                						'<img align="left" src="images/edit.png" width="25" height="25" onclick="enableQuestion('+$questionId+')"/>'+
                						'</button>'+
					                	'<button type=button style="border: 0; position: relative; top: 12px; background: transparent">'+
					                	'<img align="left" src="images/report.png" width="25" height="25" onclick="getReport('+$questionId+',\''+$questionText+'\')"/>'+
					                	'</button>'+
					                	'<button type=button style="border: 0; position: relative; top: 12px; background: transparent">'+
					                	'	<img align="left" src="images/delete.png" width="25" height="25" onclick="removeQuestion('+$questionId+')"/>'+
					                	'</button>'+	
					                	'</td>' +
						                '</tr>' +
						                '<tr>' +
						                '<td align="center">' +
						                	$answersRow +
						                '</td>' +
						               '</tr><tr><td><br/><br/></td</tr>';
			    		$('#viewQuestions_tbl tr:last').after($newRow);
			    		
			    	});	
			    	$("#recent_sessions").css("display", "none");
			    	$("#viewQuestions").css("display", "block");
			    
				    	
			    },
			    error: function(e){
			    	alert(e);
			    }
			});
		}
	        var i = 0;
	        //FUNCTION TO ADD TEXT BOX ELEMENT
	          function addElement()
	          {   
	          	i++;
	              var contentID = document.getElementById('content');
	              var newTBDiv = document.createElement('div');
	              newTBDiv.setAttribute('id','strText'+i);
	              newTBDiv.innerHTML = "<input type='text' id='text" + i + "' class='tb' name='create_q_answers'/>";
	              contentID.appendChild(newTBDiv);
	          }
	          //FUNCTION TO REMOVE TEXT BOX ELEMENT
	          function removeElement()
	          {
	              if(i != 0)
	              {
	                  var contentID = document.getElementById('content');
	                  contentID.removeChild(document.getElementById('strText'+i));
	                  i--;
	              }
	          }
	        
   </script>
	 </head>
    <body>
    	<input type = "hidden" id="current_session_id" value="" />
        <div id="recent_sessions">
        	<form>
	            <table width = "100%">
	                <tr valign="top">
	                <td align="center">
	                    <h3>CSI5130 Clicker App</h3>
	                </td>
	               	</tr>
	               	<tr>
	                <td align="center">
	                    Please select a session or <a href='javascript:showCreateSession()' >create a new session</a>
	                </td>
	                </tr>
	                <tr>
	                <td align="center">
	                	<br/><br/>
	                </td>
	                </tr>
					<tr>
	                <td align="center" id="sessions_list">
	                	
	                </td>
	                </tr>
	            </table>
        	</form>
        </div>
        <div id="create_session" style="display:none">
        	<form>
	            <table width = "100%">
	                <tr valign="top">
	                <td align="center">
	                    <h3>CSI5130 Clicker App</h3>
	                </td>
	               	</tr>
	               	<tr>
	                <td align="center">
	                    Session Keyword : <input type="text" id="create_session_keyword" /><br/><br/><br/>
	               		
	                    Session Key: <input type="password" id="create_session_key" />
	                </td>
	                </tr>
					<tr>
	                <td align="center" id="sessions_list">
	                	<br><a href="javascript:createQuestionSession()" class="button_a">Submit</a>
	                </td>
	                </tr>
	            </table>
        	</form>
        </div>
        <div id="viewQuestions"  style="display:none">
        
        	<table width = "100%" id="viewQuestions_tbl">
                <tr valign="top">
                <td align="center">
                    <h3>CSI5130 Clicker App</h3>
                </td>
               	</tr>
               	<tr valign="top">
                <td align="center">
                    <a href='javascript:backtoSessionList()' class="button_a" >Back to session list</a><br/><br/><br/>
                    <a href='javascript:showCreateQuestion()' class="button_a" >create a new question</a><br/><br/><br/>
                </td>
               	</tr>
				
            </table>
        </div>
        <div id="createQuestion" style="display:none">
        	<table width = "100%">
                <tr valign="top">
                <td align="center">
                    <h3>CSI5130 Clicker App</h3>
                </td>
               	</tr>        
               	<tr>
               		<td align ="center">
        				<a href='javascript:backtoQuestionList()' class="button_a" >Back to questions</a>
        				<br><br>
        			</td>
        		</tr>
                <tr>
                <td align="center">
                    What is the question text?
                </td>
                </tr>
                <tr>
                <td align="center">
                    <textarea id="create_q_question" name="create_q_question" rows="12" cols="26"></textarea>
                </td>
                </tr>
                <tr>
                <td align="center">
                    What are the possible answers?
                </td>
                </tr>
                <tr>
                <td align="center">

                    <span style="margin-left:90px">&nbsp;</span>
                	<input id="atext" type="text" class="tb" value="text0" name="create_q_answers">
                     <button type="button" style="border: 0; background: transparent">
                		<img src="images/plus.png" width="30" height="30" onclick="addElement()">
                	</button>
                	<button type="button" style="border: 0; background: transparent">
                		<img src="images/minus.png" width="30" height="30" onclick="removeElement()">
                	</button>
                </td>
                </tr>
                <tr>
                <td align="center">
                	<div id="content"></div>
                </td>
                </tr>
                <tr>
                <td align="center">
                    <input type="radio" id="enabled" name="enabledisable" class="regular-radio" value="true" checked/><label  for="enabled"  style="width: 100px">Enable</label>
        			<input type="radio" id="disabled" name="enabledisable" class="regular-radio"  value="false" /><label for="disabled" style="width: 100px">Disable</label><br />
                </td>
                </tr>
                <tr>
                <td align="center">
                   Please provide session key: <br/>
                   <input type="password" name="create_question_key" id="create_question_key"/> 
                </td>
                </tr>
                <tr>
                <td align="center">
                	<br>
                	<a href="javascript:createQuestion()" class="button_a">Submit</a>
                </td>
                </tr>
            </table>
        </div>
        <div id="viewReport" style="display:none">
        	<h3 align="center">CSI5130 Clicker App</h3>
        <table width = "100%" align="center">
        <tr>
        <td align ="center">
        	<a href='javascript:backtoQuestionList()' class="button_a" >Back to questions</a>
        </td>
        </tr>
        </table>
        <table width = "100%" align="center" id="viewReport_tbl">
        </table>
        </div>
    </body>
</html>